package com.ruoyi.system.runner;

import com.ruoyi.common.config.ConfigReader;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Component
@Slf4j
@Order(1) // 数值越小，优先级越高
public class RedisInitDataRunner implements ApplicationRunner {

    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(ApplicationArguments args){
        // 设置消息列表版本
        Integer preMsgOpsVersion = redisCache.getCacheObject(CacheConstants.SYNC_OPS_VERSION);
        log.info("RedisMsgVersionRunner run messageVersion：{}", preMsgOpsVersion);
        if(preMsgOpsVersion == null){
            redisCache.setCacheObject(CacheConstants.SYNC_OPS_VERSION, 1);
        }

        // 设置ProjectRootPath  当前项目的根目录
        String projectRootPath = getProjectRootPath();
        redisCache.setCacheObject(CacheConstants.PROJECT_ROOT_PATH, projectRootPath);
        log.info("RedisInitDataRunner getProjectRootPath absolutePath:{}" ,projectRootPath);

    }

    public static String getProjectRootPath() {
        try {
            // 场景1：项目以JAR包形式运行（Linux常见部署方式）
            if (isRunningInJar()) {
                String linuxPath = ConfigReader.getString("linux.root.path", "");
                log.info("RedisInitDataRunner getProjectRootPath linuxPath:{}" ,linuxPath);
                return linuxPath;
            }else {
                // 获取项目根目录，target/classes 所在的上级目录就是项目根目录
                File file = ResourceUtils.getFile("classpath:");
                String absolutePath = file.getParentFile().getParentFile().getAbsolutePath();
                int lastIndexOf = absolutePath.lastIndexOf(File.separator);
                return absolutePath.substring(0, lastIndexOf);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断当前是否以JAR包形式运行
     */
    private static boolean isRunningInJar() {
        return RedisInitDataRunner.class.getResource("RedisInitDataRunner.class").toString().startsWith("jar:");
    }


}
